﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Project.BIZ;
using Project.IBIZ;
using Project.DTO;

namespace Project.UI
{
    public partial class Login : System.Web.UI.Page
    {
        /// <summary>
        /// Global instance from Login Business layer
        /// </summary>
        ILoginBIZ LoginBiz = new LoginBIZ();

        #region "Event methods"

        /// <summary>
        /// Default first loading information
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Handle event when user clicks on button Login
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            // Check if an account is valid or not
            if (IsValidAccount() == 1)
            {
                Session.Add(Constants.SessionUserName, txtUsername.Text);
                // Redirect to DemoList page
                Response.Redirect(Constants.DefaultPage);
            }
            //txtPassword.Text = (string)Session[Constants.SessionUserName];
            //Console.Write("DONE");
        }

        /// <summary>
        /// Inform user if his/her Username or Password is incorrect
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>
        protected void InvalidAccountValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            // Check if an account is valid or not
            if (IsValidAccount() == 0)
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        #endregion

        #region "Support Methods"

        /// <summary>
        /// Indicates if an account is valid or not
        /// </summary>
        /// <returns>0: Incorrect info. 1:Valid user. 2:Inactive account</returns>
        private int IsValidAccount()
        {
            // Declare new User object's instance
            User user = new User();
            user.Username = txtUsername.Text;
            user.Password = txtPassword.Text;

            // Check if an account is valid or not
            return LoginBiz.IsValidUser(user);
        }

        #endregion
    }
}